package com.slipper.system.codeless.controller;

import com.slipper.core.gson.GsonUtil;
import com.slipper.system.backup.service.BackupRestoreService;
import com.slipper.system.codeless.bo.*;
import com.slipper.system.codeless.service.*;
import com.slipper.system.codeless.vo.PageVO;
import com.slipper.util.*;
import jakarta.annotation.Resource;

import com.slipper.constants.Constants;
import com.slipper.core.tree.Tree;
import com.slipper.core.tree.Node;
import com.slipper.core.tree.TreeInfo;
import com.slipper.core.tree.TreeUtil;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 页面信息表
 */
@RestController
@RequestMapping("/system/page")
public class PageController {
    private static final Logger logger = LoggerFactory.getLogger(PageController.class);

    @Resource
    private PageService pageService;
    @Resource
    private PageFolderService pageFolderService;
    @Resource
    private BackupRestoreService backupRestoreService;

    @PostMapping(value = "/queryBy")
    public String queryBy(@RequestBody PageBO bo) {
        if(Tool.isBlank(bo.getId())) {
            return ResultUtil.failureResult("数据获取失败！");
        }
        return ResultUtil.successResult(pageService.queryBy(bo.getId()));
    }

    @PostMapping(value = "/queryList")
    public String queryList(@RequestBody PageBO bo) {
        return ResultUtil.successResult(pageService.queryList(bo));
    }

    @PostMapping(value = "/queryPage")
    public String queryPage(@RequestBody PageBO bo) {
        return ResultUtil.successResult(pageService.queryPage(bo));
    }

    @PostMapping("/queryTree")
    public String queryTree(@RequestBody PageBO bo) {
        List<PageFolderBO> folderList = pageFolderService.queryList(new PageFolderBO());
        TreeInfo folderTreeInfo = new TreeInfo("页面");
        folderTreeInfo.setRootId(Constants.ROOT_ID);
        folderTreeInfo.setIdField("id");
        folderTreeInfo.setPidField("parentId");
        folderTreeInfo.setTextField("name");
        folderTreeInfo.setNodeType("folder");
        folderTreeInfo.setSortField("ordinal");

        List<PageBO> pageList = pageService.queryList(bo);
        TreeInfo pageTreeInfo = new TreeInfo("");
        pageTreeInfo.setIdField("id");
        pageTreeInfo.setPidField("folderId");
        pageTreeInfo.setTextField("name");
        pageTreeInfo.setNodeType("page");
        pageTreeInfo.setSortField("ordinal");

        Node rootNode = TreeUtil.buildTree(
                "asc",
                new Tree(folderTreeInfo, BeanUtil.setOrdinal(folderList)),
                new Tree(pageTreeInfo, BeanUtil.setOrdinal(pageList)));
        return ResultUtil.successResult(rootNode);
    }

    @PostMapping(value = "/queryTypeCount")
    public String queryTypeCount() {
        return ResultUtil.successResult(pageService.queryTypeCount());
    }

    @PostMapping(value = "/save")
    public String save(@RequestBody PageBO bo) {
        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(pageService.save(bo), bo);
    }

    @PostMapping(value = "/updateFolder")
    public String updateFolder(@RequestBody PageBO bo) {
        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.saveResult(pageService.updateFolder(bo), bo);
    }

    @PostMapping(value = "/delete")
    public String delete(@RequestBody PageBO bo) {
        return ResultUtil.deleteResult(pageService.delete(bo));
    }

    @PostMapping(value = "/copy")
    public String copy(@RequestBody PageBO bo) {
        bo.setOperateId(Constants.getCurrentUser().getEmployeeId());
        return ResultUtil.operateResult(pageService.copy(bo), "复制");
    }

    @PostMapping(value = "/relation/{pageId}")
    public String queryRelation(@PathVariable("pageId") String pageId) {
        return ResultUtil.successResult(pageService.queryRelation(pageId));
    }

    @PostMapping(value = "/exportData")
    public void exportData(HttpServletResponse response, @RequestBody Map<String, Object> data) {
        String fileName = "page-" + DateUtil.format(new Date(), "dd-HH-mm-ss") + ".dat";
        PageVO vo = backupRestoreService.backupPage(data);
        FileUtil.downloadContent(response, fileName, AESUtil.encrypt(GsonUtil.toJson(vo)));
    }

    @PostMapping(value = "/importData")
    public String importData(PageBO bo) {
        if (bo.getFile() == null) {
            return ResultUtil.failureResult("请选择上传文件！");
        }

        try {
            String content = new String(bo.getFile().getBytes(), StandardCharsets.UTF_8);
            backupRestoreService.restorePage(AESUtil.decrypt(content));
            return ResultUtil.successResult("导入页面成功。");
        } catch (Exception e) {
            logger.error("文件解释出错！", e);
            return ResultUtil.failureResult("文件解释出错！");
        }
    }
}
